package com.linshengjian.snowball.core;

import com.linshengjian.snowball.core.annotation.AutowiredDataWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;

@Configuration
public class CoreConfig {

    @Autowired
    private DataManager manager;

    @Bean
    public DataManager manager() {
        return new DataManager();
    }

    @Bean
    public BeanPostProcessor processor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                return bean;
            }

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                Field[] fields = bean.getClass().getDeclaredFields();
                for (Field field: fields) {
                    AutowiredDataWrapper annotation = field.getAnnotation(AutowiredDataWrapper.class);
                    if (annotation == null) continue;

                    Class type = annotation.value();
                    DataWrapper wrapper = manager.get(type);

                    boolean is = field.isAccessible();
                    field.setAccessible(true);

                    try {
                        field.set(bean, wrapper);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    field.setAccessible(is);
                }
                return bean;
            }
        };
    }
}
